package com.anysoft.web;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.WebViewNetworkProtocol;
import com.anysoft.bean.AttentionsCommandBean;
import com.anysoft.bean.QueryAttentionByFundcodeBean;
import com.anysoft.event.TimeOutEvent;
import com.anysoft.me.base.BaseFundWebViewActivity;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.MentorLogger;
import com.anysoft.utils.StringUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import butterknife.OnClick;

/**
 * Created by lty on 2017/11/13.
 * 投资目标及投资范围
 */

public class FundInvestDetailActivity extends BaseFundWebViewActivity {

    private String param, url_title, fundname, fundcode, subInfoTitle, fundstateid, fundType;
    public boolean isFollow = false;
    private String token = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        SharePopup.setOnShareEventLinstener(new OnShareEventLinstenerImpl() {
//            @Override
//            public void onShareSuccess() {
//                AnalyticsEventUtils.toShareFundEvent(FundInvestDetailActivity.this);
//            }
//        });
        getIntentVaule();
        generateUrl(url_title, param);
        rightButton.setVisibility(View.VISIBLE);
        cmtv_title.setText(fundname + " " + fundcode);
        setWebViewConfig(loadUrl);
        if (!StringUtils.isNullOrEmpty(subInfoTitle)) {
            subTitle.setText(subInfoTitle);
        }
        if (!TextUtils.isEmpty(getFundCustomerNo())) {
            queryAttentionByFundcode();
        }

        if (!TextUtils.isEmpty(fundcode)) {
            queryFundInfo(fundcode);
        }
    }

    private void getIntentVaule() {
        fundname = getIntent().getStringExtra("fundName");
        fundcode = getIntent().getStringExtra("fundCode");
        url_title = getIntent().getStringExtra("url_title");
        subInfoTitle = getIntent().getStringExtra("infoTitle");
        param = getIntent().getStringExtra("param");
        fundType = getIntent().getStringExtra("fundType");
        fundstateid = getIntent().getStringExtra("fundstateid");
        token = getToken();
    }

    @Override
    public void onshouldOverrideUrlLoadingCallBack(WebView webview, String url) {
        String url_decode = null;
        try {
            url_decode = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MentorLogger.Log(TAG, "url_decode=" + url_decode);
        String mainTitle;
        String infoTitle;
        Map<String, String> map = new HashMap<>();
        String[] params = url_decode.split("\\?")[1].split("&");
        for (int i = 0; i < params.length; i++) {
            String key = params[i].split("=")[0];
            String value = "";
            try {
                value = params[i].split("=")[1];
            } catch (Exception exception) {
                MentorLogger.Log(TAG, "value为null");
            }
            map.put(key, value);
        }

        mainTitle = fundname + " " + fundcode;
        infoTitle = map.get("infoTitle");
        if (url.contains("fundBuy")) { //购买
            mIntent.setClass(mActivity, AssetsFundBuyActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("mainTitle", mainTitle);
            startActivity(mIntent);
        } else if (url.contains("fundInvestAdd.html")) { //定投
            mIntent.setClass(mActivity, AssetsFundInvestAddActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            mIntent.putExtra("mainTitle", mainTitle);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_LOGIN)) {
            ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
        } else if (url.contains(WebViewNetworkProtocol.GO_QUESTION)) {
            startRiskActivity(null);
        } else if (url.contains(WebViewNetworkProtocol.GOTO_E_CHART)) {
            mIntent.setClass(mActivity, FundDetailEchartActivity.class);
            String param = url.split("\\?")[1];
            mIntent.putExtra("param", param);
            startActivity(mIntent);
        } else if (url.contains(WebViewNetworkProtocol.GO_MOD_USER_INFO)) {
            ActivityUtils.gotoUserInfoMod(mActivity, MOD_USER_INFO);
        } else if (url.contains(WebViewNetworkProtocol.GO_EDIT_MOBILE)) {
            ActivityUtils.gotoUserMobileMod(mActivity, MOD_USER_MOBILE);
        } else {
            webview.loadUrl(url);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!token.equals(getToken())) {
            token = getToken();
            generateUrl(url_title, HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" + fundcode + "&fundName=" +
                    fundname
                    + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid + "&fundType=" + fundType
                    + "&infoTitle=" + subInfoTitle);

            if (CommonUtil.isNetWorkConnected(mActivity)) {
                reLoadPage(loadUrl);
            }
        }

        if (!TextUtils.isEmpty(getFundCustomerNo())) {
            queryAttentionByFundcode();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeOutCallBack(TimeOutEvent event) {
        if (event.isSuccess) {
            finish();
        }
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.shareButton})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftButton:
                finish();
                break;
            case R.id.rightButton:
                if (!isFastDoubleClick()) {
                    if (mentorApplication.needLogin()) {
                        ActivityUtils.gotoLogin(mActivity, hasUser(), false, findUserId());
                    } else {
                        if (isFollow) {
                            attentionsCommand(0);
                        } else {
                            attentionsCommand(1);
                        }
                    }
                }
                break;
            case R.id.shareButton:
                if (!isFastDoubleClick()) {
                    //请求查询基金接口获取近一年收益值
                    String periodYearOne = getFundPeriodYearOne();

                    String url = HostConstant.HOST_WEB_URL_HEADER + String.format("fundDetailSec.html?fundCode=%s&fundType=%s", fundcode, fundType);
//                    SharePopup.Share(mActivity, mActivity.getResources().getString(R.string.share_title), url, fundname + " " +
//                            "" + fundcode + "\n近一年收益率" + periodYearOne);
                }
                break;
        }
    }

    /**
     * 取消/添加关注
     *
     * @param action 0为取消关注，１为添加关注
     */
    private void attentionsCommand(int action) {
        Map<String, String> params = new HashMap<>();

        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundcode);
        params.put("action", action + "");

        OkGo.<String>post(HostConstant.ATTENTIONS_COMMAND)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateAttentionsCommand(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void UpdateAttentionsCommand(String json) {

        AttentionsCommandBean bean;
        try {
            bean = new Gson().fromJson(json, AttentionsCommandBean.class);
        } catch (Exception exception) {
            showConfirmAlert(mActivity, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }

        if (bean.isData()) {
            if (isFollow) {
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                showToast("取消关注成功");
            } else {
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                showToast("添加关注成功");
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (MOD_USER_INFO == requestCode || MOD_USER_MOBILE == requestCode) {
            token = getToken();
            generateUrl(url_title, HttpUtils.getCommonParams2StringByWeb(mActivity) + "&fundCode=" + fundcode + "&fundName=" +
                    fundname
                    + "&cusNo=" + getFundCustomerNo() + "&fundstateid=" + fundstateid + "&fundType=" + fundType);

            if (CommonUtil.isNetWorkConnected(mActivity)) {
                reLoadPage(loadUrl);
            }
            if (!TextUtils.isEmpty(getFundCustomerNo())) {
                queryAttentionByFundcode();
            }
        }
    }

    private void queryAttentionByFundcode() {
        Map<String, String> params = new HashMap<>();
        params.put("fundCustomerNo", getFundCustomerNo());
        params.put("fundCode", fundcode);
        OkGo.<String>post(HostConstant.QUERY_ATTENTIONS_BY_FUNDCODE)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateUI(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }


    private void UpdateUI(String resultJson) {

        QueryAttentionByFundcodeBean bean;

        try {
            bean = new Gson().fromJson(resultJson, QueryAttentionByFundcodeBean.class);
        } catch (Exception e) {
            Logger.e(TAG, "Gson解析数据时发生异常");
            e.printStackTrace();
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, resultJson)) {
            return;
        }

        if (bean.getData() == null) {
            showConfirmAlert(mActivity, "数据为空");
            return;
        }

        switch (bean.getData().getIsAttention()) {
            case 0:
                isFollow = false;
                rightButton.setBackgroundResource(R.mipmap.nav_like_white);
                break;
            case 1:
                isFollow = true;
                rightButton.setBackgroundResource(R.mipmap.nav_like_ac_white);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
